//
//  MyOrderViewController.m
//  LogisticsFollow
//
//  Created by JustFei on 2016/12/17.
//  Copyright © 2016年 manridy. All rights reserved.
//

#import "MyOrderViewController.h"
#import "BJNoDataView.h"
#import "OrderModel.h"
#import "OrderTableViewCell.h"
#import "MJRefresh.h"
#import "SearchViewController.h"
#import "OrderParticularsViewController.h"

@interface MyOrderViewController () < UITableViewDelegate , UITableViewDataSource >
@property (weak, nonatomic) IBOutlet UIButton *unFinish;
@property (weak, nonatomic) IBOutlet UIButton *finish;
@property (weak, nonatomic) IBOutlet UIView *unFinishView;
@property (weak, nonatomic) IBOutlet UIView *finishView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic ,strong) NSMutableArray *finishDataArr;
@property (nonatomic ,strong) MBProgressHUD *hud;

@end

@implementation MyOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self createUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)createUI
{
    self.navigationItem.title = @"订单列表";
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    rightButton.frame = XXF_CGRectMake(0, 0, 44, 44);
    [rightButton addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = backItem;
    
    self.unFinish.selected = YES;
    self.finish.selected = NO;
    [self.unFinish setTitleColor:kUIColorFromHEX(0x3a95e7, 1) forState:UIControlStateNormal];
    self.unFinishView.hidden = NO;
    self.finishView.hidden = YES;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"OrderTableViewCell" bundle:nil] forCellReuseIdentifier:@"MyOrderCell"];
    self.tableView.estimatedRowHeight = 200;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //Call this Block When enter the refresh status automatically
        [self getData];
    }];
    
    [self addObserver:self forKeyPath:@"dataArr" options:NSKeyValueObservingOptionNew context:nil];
    [self addObserver:self forKeyPath:@"finishDataArr" options:NSKeyValueObservingOptionNew context:nil];
    if (self.dataArr.count == 0) {
        self.dataArr = [NSMutableArray array];
    }
}

//获取订单信息
- (void)getData
{
    [self buttonEnable];
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //服务器给的域名
    NSString *domainStr;
    
    if (self.finish.selected) {
        domainStr = kHistoryOrderPort;
    }else {
        domainStr = kNewOrderPort;
    }
    
    //假如需要提交给服务器的参数是key＝1,class_id=100
    //创建一个可变字典
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    NSString *guid = [[NSUserDefaults standardUserDefaults] objectForKey:@"guid"];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:guid forKey:@"guid"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
        [manager POST:domainStr parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 隐藏系统风火轮
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            
            //json解析
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            //转成jsonModel
            OrderModel *model = [[OrderModel alloc] initWithDictionary:resultDic error:nil ];
            NSLog(@"isSuccess = %d\nmsg = %@\nresult = %@",model.isSuccess ,model.msg ,model.result);
            if (model.isSuccess) {
                if (self.finish.selected) {
                    self.finishDataArr = [NSMutableArray arrayWithArray:model.result];
                }else {
                    self.dataArr = [NSMutableArray arrayWithArray:model.result];
                }
                
                [self.tableView reloadData];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.tableView.mj_header endRefreshing];
                });
            }else {
                [self doFailPOST];
            }
            [self buttonAble];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            [self doFailPOST];
            [self buttonAble];
        }];
}

- (void)doFailPOST
{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.mode = MBProgressHUDModeText;
    self.hud.label.text = @"请求失败，请确认网络后重试";
    [self.hud hideAnimated:YES afterDelay:1.5];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_header endRefreshing];
    });
}

- (void)buttonEnable
{
    self.finish.enabled = NO;
    self.unFinish.enabled = NO;
}

- (void)buttonAble
{
    self.finish.enabled = YES;
    self.unFinish.enabled = YES;
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.unFinish.selected ? self.dataArr.count : self.finishDataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyOrderCell"];
    
    NSArray *arr = self.unFinish.selected ? self.dataArr : self.finishDataArr;
    cell.model = arr[indexPath.section];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = kUIColorFromHEX(0xf5f6f6, 1);
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.unFinish.selected ? 370 : 310;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    OrderParticularsViewController *vc = [[OrderParticularsViewController alloc] initWithNibName:@"OrderParticularsViewController" bundle:nil];
    NSArray *modelArr = self.unFinish.selected ? self.dataArr : self.finishDataArr;
    vc.model = modelArr[indexPath.section];
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - ----KVO回调----
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if (![keyPath isEqualToString:@"dataArr"] && ![keyPath isEqualToString:@"finishDataArr"]) {
        return;
    }
    
    if (self.unFinish.selected) {
        if ([self.dataArr count] == 0) {//无数据
            [[BJNoDataView noDataView] showCenterWithSuperView:self.tableView icon:nil];
            
            return;
        }
        
        //有数据
        [[BJNoDataView noDataView] clear];
    }else {
        if ([self.finishDataArr count] == 0) {
            [[BJNoDataView noDataView] showCenterWithSuperView:self.tableView icon:nil];
            
            return;
        }
        
        [[BJNoDataView noDataView] clear];
    }
    
}

-(void)dealloc{
    //移除KVO
    [self removeObserver:self forKeyPath:@"dataArr"];
}

#pragma mark - Action
- (IBAction)unFinishAction:(UIButton *)sender
{
    if (!sender.selected) {
        sender.selected = YES;
        [sender setTitleColor:kUIColorFromHEX(0x3a95e7, 1) forState:UIControlStateNormal];
        self.unFinishView.hidden = NO;
        
        self.finish.selected = NO;
        self.finishView.hidden = YES;
        [self.finish setTitleColor:kBlackColor forState:UIControlStateNormal];
        
        [self.tableView reloadData];
    }
}

- (IBAction)finishAction:(UIButton *)sender
{
    if (!sender.selected) {
        sender.selected = YES;
        self.finishView.hidden = NO;
        [sender setTitleColor:kUIColorFromHEX(0x3a95e7, 1) forState:UIControlStateNormal];
        
        self.unFinish.selected = NO;
        self.unFinishView.hidden = YES;
        [self.unFinish setTitleColor:kBlackColor forState:UIControlStateNormal];
        
        [self.tableView reloadData];
    }
}

- (void)searchAction:(UIButton *)sender
{
    SearchViewController *vc = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    
    return _dataArr;
}


@end
